package logic

import (
	"MyBlogv2/Servers/UserAction/internal/svc"
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"
	"strconv"

	"MyBlogv2/Servers/UserAction/userAction"

	"github.com/zeromicro/go-zero/core/logx"
)

type IsLikeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewIsLikeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IsLikeLogic {
	return &IsLikeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *IsLikeLogic) IsLike(in *UserAction.UserActionRequest) (*UserAction.IsLikeResponse, error) {
	typeOfLike := int(in.Type)
	typeId := int(in.TypeId)
	userId := int(in.UserId)

	if typeOfLike == define.LIKE_TYPE_ARTICLE {
		var likeVoList []models.LikeVo
		var likeVoRsponseList []*UserAction.LikeVo
		var dbCount int64
		models.Db.Model(new(models.LikeVo)).Where("user_id = ? and type = ? and type_id = ?", userId, typeOfLike, typeId).Count(&dbCount).Find(&likeVoList)
		for i, v := range likeVoList {
			likeVoList[i].IdStr = strconv.Itoa(v.Id)
		}
		if dbCount > 0 {
			copier.Copy(&likeVoRsponseList, &likeVoList)
			for i, v := range likeVoList {
				likeVoRsponseList[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
				likeVoRsponseList[i].UpdateTime = helper.MyTimeToTimestamp(v.UpdateTime)
				likeVoRsponseList[i].Id = v.IdStr

			}
			return &UserAction.IsLikeResponse{
				Code: int64(HttpCode.SUCCESS.GetCode()),
				Data: likeVoRsponseList,
			}, nil
		} else {
			return &UserAction.IsLikeResponse{
				Code: int64(HttpCode.FAILURE.GetCode()),
			}, nil
		}

	}

	if typeOfLike == define.LIKE_TYPE_COMMENT || typeOfLike == define.LIKE_TYPE_LEAVE_WORD {
		var likeVoList []models.LikeVo
		var likeVoRsponseList []*UserAction.LikeVo
		var dbCount int64
		db := models.Db.Model(new(models.LikeVo))
		if typeOfLike == define.LIKE_TYPE_LEAVE_WORD {
			db = db.Where("type_id = ?", typeId)
		}
		db.Where("user_id = ? and type = ?", userId, typeOfLike).Count(&dbCount).Find(&likeVoList)
		for i, v := range likeVoList {
			likeVoList[i].IdStr = strconv.Itoa(v.Id)
		}
		if dbCount > 0 {
			copier.Copy(&likeVoRsponseList, &likeVoList)
			for i, v := range likeVoList {
				likeVoRsponseList[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
				likeVoRsponseList[i].UpdateTime = helper.MyTimeToTimestamp(v.UpdateTime)
				likeVoRsponseList[i].Id = v.IdStr

			}
			return &UserAction.IsLikeResponse{
				Code: int64(HttpCode.SUCCESS.GetCode()),
				Data: likeVoRsponseList,
			}, nil
		} else {
			return &UserAction.IsLikeResponse{
				Code: int64(HttpCode.FAILURE.GetCode()),
			}, nil
		}

	}
	return &UserAction.IsLikeResponse{
		Code: int64(HttpCode.FAILURE.GetCode()),
	}, nil

}
